<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '计划详情',
  },
}
</route>

<script setup lang="ts">
import type { PlanDailyTaskRespVO, ReadingPlanDetailRespVO } from '@/api/types/plan'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { computed, reactive, ref } from 'vue'
import {
  completeTask,
  deleteReadingPlan,
  getPlanTasks,
  getReadingPlanDetail,
  resetTask,
  skipTask,
} from '@/api/plan'
import { formatDate, formatTime } from '@/utils/date'

// 页面参数
const planId = ref('')

// 移除了导航标签相关代码

// 加载状态
const loading = ref(false)
const tasksLoading = ref(false)

// 计划详情数据
const planDetail = ref<ReadingPlanDetailRespVO | null>(null)

// 计划任务数据
const dailyTasks = ref<PlanDailyTaskRespVO[]>([])
const selectedTask = ref<PlanDailyTaskRespVO | null>(null)
const showActionSheet = ref(false)

// 任务操作状态
const taskOperation = reactive({
  loading: false,
  type: '',
  taskId: 0,
})

// 计算属性：按日期分组的任务
const groupedTasks = computed(() => {
  if (!dailyTasks.value || dailyTasks.value.length === 0)
    return []

  // 按日期分组
  const groups: Record<string, any> = {}

  dailyTasks.value.forEach((task) => {
    const dateStr = formatDate(new Date(task.taskDate))
    if (!groups[dateStr]) {
      groups[dateStr] = {
        date: dateStr,
        tasks: [],
        completedCount: 0,
      }
    }

    groups[dateStr].tasks.push(task)
    if (task.status === 'completed') {
      groups[dateStr].completedCount++
    }
  })

  // 转换为数组并按日期排序
  return Object.values(groups).sort((a, b) => {
    return new Date(a.date).getTime() - new Date(b.date).getTime()
  })
})

// 计算属性
const sortedDays = computed(() => {
  if (!planDetail.value?.bookListByDay)
    return []
  return Object.keys(planDetail.value.bookListByDay)
    .map(day => Number.parseInt(day))
    .sort((a, b) => a - b)
})

const hasAnyBooks = computed(() => {
  return sortedDays.value.length > 0
})

// 获取计划基本信息（兼容新旧数据结构）
const planInfo = computed(() => {
  if (planDetail.value) {
    return {
      planName: planDetail.value.planName || '未知计划',
      totalDays: Number(planDetail.value.estimatedDays) || 0,
      currentDay: Number(planDetail.value.currentDay) || 1,
      status: planDetail.value.status || 'active',
    }
  }
  return {
    planName: '加载中...',
    totalDays: 0,
    currentDay: 1,
    status: 'active',
  }
})

// 计划管理菜单
function managePlan() {
  if (!planDetail.value?.id)
    return

  uni.showActionSheet({
    itemList: ['删除计划'],
    success: (res) => {
      if (res.tapIndex === 0) {
        handlePlanAction('删除计划')
      }
    },
  })
}

// 处理计划操作
async function handlePlanAction(action: string) {
  if (action === '删除计划') {
    await deletePlan()
  }
}

async function deletePlan() {
  if (!planDetail.value?.id)
    return

  uni.showModal({
    title: '确认删除',
    content: '是否删除该计划？删除后无法恢复。',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '删除中...' })
          const response = await deleteReadingPlan(planDetail.value!.id)

          if (response && response.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success',
            })

            // 发送计划变更事件，通知首页更新数据
            uni.$emit('planChanged')

            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          }
          else {
            throw new Error(response?.msg || '删除失败')
          }
        }
        catch (error) {
          console.error('删除计划失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'none',
          })
        }
        finally {
          uni.hideLoading()
        }
      }
    },
  })
}

function sharePlan() {
  uni.showActionSheet({
    itemList: ['复制链接', '生成二维码'],
    success: (res) => {
      if (res.tapIndex === 0) {
        // 复制链接
        uni.setClipboardData({
          data: `https://example.com/plan/${planDetail.value.id}`,
          success: () => {
            uni.showToast({
              title: '链接已复制',
              icon: 'success',
            })
          },
        })
      }
      else if (res.tapIndex === 1) {
        // 生成二维码
        uni.showToast({
          title: '二维码功能开发中',
          icon: 'none',
        })
      }
    },
  })
}

function openBook(book: any, task?: PlanDailyTaskRespVO) {
  const bookId = book.bookId || book.id
  const title = book.title || book.bookTitle

  // 构建URL参数
  let url = `/pages-sub/reading/picture-book-reader/index?bookId=${bookId}&title=${encodeURIComponent(title)}`

  // 如果有计划相关信息，添加到URL参数中
  if (planId.value) {
    url += `&planId=${planId.value}`
  }
  if (task?.id) {
    url += `&taskId=${task.id}`
  }

  uni.navigateTo({ url })
}

// 处理任务点击
function handleTaskClick(task: PlanDailyTaskRespVO) {
  if (task.status === 'completed') {
    // 已完成的任务，跳转到阅读器查看
    openBook(task, task)
  }
  else {
    // 未完成的任务，显示操作选项
    showTaskActions(task)
  }
}

// 显示任务操作菜单
function showTaskActions(task: PlanDailyTaskRespVO) {
  selectedTask.value = task

  const actions = []

  if (task.status === 'pending') {
    actions.push('标记完成', '开始阅读') // 跳过任务
  }
  else if (task.status === 'completed') {
    actions.push('重新阅读', '重置任务')
  }
  else if (task.status === 'skipped') {
    actions.push('标记完成', '开始阅读', '重置任务')
  }

  uni.showActionSheet({
    itemList: actions,
    success: (res) => {
      const action = actions[res.tapIndex]
      handleTaskAction(task, action)
    },
  })
}

// 处理任务操作
async function handleTaskAction(task: PlanDailyTaskRespVO, action: string) {
  switch (action) {
    case '标记完成':
      await markTaskCompleted(task)
      break
    case '跳过任务':
      await markTaskSkipped(task)
      break
    case '开始阅读':
    case '重新阅读':
      openBook(task, task)
      break
    case '重置任务':
      await resetTaskStatus(task)
      break
  }
}

// 标记任务完成
async function markTaskCompleted(task: PlanDailyTaskRespVO) {
  try {
    taskOperation.loading = true
    taskOperation.type = 'complete'
    taskOperation.taskId = task.id

    const response = await completeTask(task.id, 10)

    if (response && response.code === 0) {
      // 更新本地任务状态
      const taskIndex = dailyTasks.value.findIndex(t => t.id === task.id)
      if (taskIndex !== -1) {
        dailyTasks.value[taskIndex].status = 'completed'
        dailyTasks.value[taskIndex].completedTime = new Date().toISOString()
      }

      // 刷新计划详情以获取最新的进度信息
      if (planId.value) {
        loadPlanDetail(planId.value)
      }

      // 发送计划变更事件，通知首页更新数据（因为计划进度可能发生变化）
      uni.$emit('planChanged')
      console.log('📢 任务完成后已触发planChanged事件，通知首页刷新计划数据')

      uni.showToast({
        title: '任务已完成',
        icon: 'success',
      })
    }
    else {
      throw new Error(response?.msg || '操作失败')
    }
  }
  catch (error: any) {
    console.error('标记任务完成失败:', error)
    uni.showToast({
      title: error.message || '操作失败',
      icon: 'none',
    })
  }
  finally {
    taskOperation.loading = false
    taskOperation.type = ''
    taskOperation.taskId = 0
  }
}

// 跳过任务
async function markTaskSkipped(task: PlanDailyTaskRespVO) {
  try {
    taskOperation.loading = true
    taskOperation.type = 'skip'
    taskOperation.taskId = task.id

    const response = await skipTask(task.id, '用户跳过')

    if (response && response.code === 0) {
      // 更新本地任务状态
      const taskIndex = dailyTasks.value.findIndex(t => t.id === task.id)
      if (taskIndex !== -1) {
        dailyTasks.value[taskIndex].status = 'skipped'
      }

      // 刷新计划详情以获取最新的进度信息
      if (planId.value) {
        loadPlanDetail(planId.value)
      }

      // 发送计划变更事件，通知首页更新数据（因为计划进度可能发生变化）
      uni.$emit('planChanged')

      uni.showToast({
        title: '任务已跳过',
        icon: 'success',
      })
    }
    else {
      throw new Error(response?.msg || '操作失败')
    }
  }
  catch (error: any) {
    console.error('跳过任务失败:', error)
    uni.showToast({
      title: error.message || '操作失败',
      icon: 'none',
    })
  }
  finally {
    taskOperation.loading = false
    taskOperation.type = ''
    taskOperation.taskId = 0
  }
}

// 重置任务状态
async function resetTaskStatus(task: PlanDailyTaskRespVO) {
  try {
    taskOperation.loading = true
    taskOperation.type = 'reset'
    taskOperation.taskId = task.id

    const response = await resetTask(task.id)

    if (response && response.code === 0) {
      // 更新本地任务状态
      const taskIndex = dailyTasks.value.findIndex(t => t.id === task.id)
      if (taskIndex !== -1) {
        dailyTasks.value[taskIndex].status = 'pending'
        dailyTasks.value[taskIndex].completedTime = null
      }

      // 刷新计划详情以获取最新的进度信息
      if (planId.value) {
        loadPlanDetail(planId.value)
      }

      // 发送计划变更事件，通知首页更新数据（因为计划进度可能发生变化）
      uni.$emit('planChanged')

      uni.showToast({
        title: '任务已重置',
        icon: 'success',
      })
    }
    else {
      throw new Error(response?.msg || '操作失败')
    }
  }
  catch (error: any) {
    console.error('重置任务失败:', error)
    uni.showToast({
      title: error.message || '操作失败',
      icon: 'none',
    })
  }
  finally {
    taskOperation.loading = false
    taskOperation.type = ''
    taskOperation.taskId = 0
  }
}

// 页面加载
onLoad((options) => {
  if (options?.planId) {
    planId.value = options.planId
    // 加载计划详情和任务数据
    loadPlanDetail(options.planId)
    loadPlanTasks(options.planId)
  }
})

// 页面显示时刷新计划详情和任务状态
onShow(() => {
  if (planId.value) {
    // 添加延迟确保阅读器页面的数据保存操作已完成
    // 增加延迟时间，确保后端任务状态同步完成
    setTimeout(() => {
      console.log('计划详情页面onShow - 开始刷新数据')
      // 同时刷新计划详情和任务列表，确保状态同步
      loadPlanDetail(planId.value)
      loadPlanTasks(planId.value)
    }, 500) // 增加到500ms，确保后端处理完成
  }
})

// 加载计划详情
async function loadPlanDetail(id: string) {
  try {
    loading.value = true
    const response = await getReadingPlanDetail(Number(id))

    if (response && response.code === 0) {
      planDetail.value = response.data
      console.log('计划详情加载成功:', planDetail.value)
      console.log('estimatedDays:', planDetail.value?.estimatedDays, 'currentDay:', planDetail.value?.currentDay)
    }
    else {
      console.warn('计划详情API响应格式异常:', response)
      throw new Error('API响应格式异常')
    }
  }
  catch (error) {
    console.error('加载计划详情失败:', error)
    uni.showToast({
      title: '加载计划详情失败',
      icon: 'error',
    })
  }
  finally {
    loading.value = false
  }
}

// 加载计划任务
async function loadPlanTasks(id: string) {
  try {
    tasksLoading.value = true
    const response = await getPlanTasks(Number(id))

    if (response && response.code === 0) {
      dailyTasks.value = response.data || []
      console.log('计划任务加载成功:', dailyTasks.value.length, '个任务')
    }
    else {
      console.warn('计划任务API响应格式异常:', response)
      dailyTasks.value = []
      uni.showToast({
        title: '加载任务失败',
        icon: 'none',
      })
    }
  }
  catch (error) {
    console.error('加载计划任务失败:', error)
    dailyTasks.value = []
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
    })
  }
  finally {
    tasksLoading.value = false
  }
}
</script>

<template>
  <view class="plan-detail-container">
    <!-- 计划标题区 -->
    <view class="plan-header">
      <view class="plan-info">
        <view class="plan-icon">
          <uni-icons type="calendar" size="24" color="#007AFF" />
        </view>
        <view class="plan-content">
          <view class="plan-title-row">
            <text class="plan-name">
              {{ planInfo.planName }}
            </text>
          </view>
          <text class="plan-progress">
            第{{ planInfo.currentDay }}/{{ planInfo.totalDays }}天
          </text>
        </view>
      </view>
      <view class="plan-actions">
        <view class="action-btn" @click="managePlan">
          <uni-icons type="more-filled" size="18" color="#666" />
        </view>
      </view>
    </view>

    <!-- 分享按钮 -->
    <view class="share-section">
      <view class="share-btn" @click="sharePlan">
        <uni-icons type="redo" size="16" color="#007AFF" />
        <text class="share-text">
          分享计划
        </text>
      </view>
    </view>

    <!-- 计划内容 -->
    <scroll-view class="plan-content-scroll" scroll-y>
      <view class="plan-detail-content">
        <!-- 加载状态 -->
        <view v-if="loading" class="loading-container">
          <uni-icons type="spinner-cycle" size="24" color="#007AFF" />
          <text class="loading-text">
            加载中...
          </text>
        </view>

        <!-- 每日任务 -->
        <view v-else-if="dailyTasks && dailyTasks.length > 0">
          <view v-for="(dayTasks, dayIndex) in groupedTasks" :key="dayIndex" class="daily-task">
            <view class="day-header">
              <view class="day-info">
                <text class="day-title">
                  {{ dayTasks.date }}
                </text>
                <text class="day-subtitle">
                  {{ dayTasks.tasks.length }}个任务
                </text>
              </view>
              <view class="day-progress">
                <text class="progress-text">
                  {{ dayTasks.completedCount }}/{{ dayTasks.tasks.length }}
                </text>
                <view class="progress-bar">
                  <view
                    class="progress-fill"
                    :style="{ width: `${dayTasks.completedCount / dayTasks.tasks.length * 100}%` }"
                  />
                </view>
              </view>
            </view>

            <view class="task-list">
              <view
                v-for="task in dayTasks.tasks"
                :key="task.id"
                class="task-card"
                :class="{
                  completed: task.status === 'completed',
                  pending: task.status === 'pending',
                  skipped: task.status === 'skipped',
                }"
                @click="handleTaskClick(task)"
              >
                <view class="task-status">
                  <view
                    class="status-icon"
                    :class="task.status"
                  >
                    <uni-icons
                      v-if="task.status === 'completed'"
                      type="checkmarkempty"
                      size="14"
                      color="#fff"
                    />
                    <uni-icons
                      v-else-if="task.status === 'skipped'"
                      type="close"
                      size="14"
                      color="#fff"
                    />
                    <text v-else class="pending-dot" />
                  </view>
                </view>

                <image
                  class="task-cover"
                  :src="task.bookCover || '/static/images/default-book.png'"
                  mode="aspectFill"
                />

                <view class="task-info">
                  <text class="task-title">
                    {{ task.bookTitle }}
                  </text>
                  <view class="task-meta">
                    <text
                      class="task-type"
                      :class="{ review: task.isReview }"
                    >
                      {{ task.isReview ? '复习' : '新学' }}
                    </text>
                    <text v-if="task.completedTime" class="completed-time">
                      {{ formatTime(task.completedTime) }}
                    </text>
                  </view>
                </view>

                <view class="task-actions" @click.stop="showTaskActions(task)">
                  <uni-icons type="more-filled" size="16" color="#999" />
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-else class="empty-state">
          <uni-icons type="info" size="48" color="#ccc" />
          <text class="empty-text">
            该计划暂无安排，请先创建任务
          </text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss" scoped>
.plan-detail-container {
  min-height: 100vh;
  background-color: #f4f4f4;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;

  .loading-text {
    margin-top: 10px;
    font-size: 14px;
    color: #666;
  }
}

.plan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #fff;
  margin-bottom: 10px;

  .plan-info {
    display: flex;
    align-items: center;
    flex: 1;

    .plan-icon {
      width: 48px;
      height: 48px;
      background-color: #f0f8ff;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
    }

    .plan-content {
      flex: 1;

      .plan-title-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 4px;

        .plan-name {
          display: block;
          font-size: 18px;
          font-weight: 600;
          color: #333;
          flex: 1;
        }

        .plan-status {
          padding: 4px 8px;
          border-radius: 12px;
          font-size: 12px;
          margin-left: 8px;

          .status-text {
            font-weight: 500;
          }

          &.status-active {
            background-color: #e6f7ff;

            .status-text {
              color: #1890ff;
            }
          }

          &.status-paused {
            background-color: #fff7e6;

            .status-text {
              color: #fa8c16;
            }
          }

          &.status-completed {
            background-color: #f6ffed;

            .status-text {
              color: #52c41a;
            }
          }

          &.status-cancelled {
            background-color: #fff1f0;

            .status-text {
              color: #ff4d4f;
            }
          }
        }
      }

      .plan-progress {
        display: block;
        font-size: 14px;
        color: #666;
      }
    }
  }

  .plan-actions {
    display: flex;
    gap: 10px;

    .action-btn {
      width: 36px;
      height: 36px;
      background-color: #f5f5f5;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;

      &:active {
        background-color: #e5e5e5;
      }
    }
  }
}

.share-section {
  padding: 0 20px 15px;

  .share-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 8px 16px;
    background-color: #f0f8ff;
    border-radius: 20px;
    align-self: flex-start;

    .share-text {
      font-size: 14px;
      color: #007aff;
    }

    &:active {
      background-color: #e0f0ff;
    }
  }
}

.nav-tabs {
  display: flex;
  background-color: #fff;
  margin-bottom: 10px;

  .tab-item {
    flex: 1;
    padding: 15px;
    text-align: center;
    border-bottom: 2px solid transparent;

    &.active {
      border-bottom-color: #007aff;

      .tab-text {
        color: #007aff;
        font-weight: 600;
      }
    }

    .tab-text {
      font-size: 16px;
      color: #666;
    }
  }
}

.plan-content-scroll {
  flex: 1;
  height: calc(100vh - 200px);
}

.plan-detail-content {
  padding: 0 15px 20px;
}

.daily-task {
  margin-bottom: 20px;

  .day-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;

    .day-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }

    .completed-badge {
      width: 20px;
      height: 20px;
      background-color: #52c41a;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .book-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
}

.book-card {
  display: flex;
  align-items: center;
  padding: 12px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

  &:active {
    background-color: #f5f5f5;
  }

  .book-cover {
    width: 60px;
    height: 80px;
    border-radius: 4px;
    margin-right: 12px;
  }

  .book-info {
    flex: 1;

    .book-title {
      display: block;
      font-size: 16px;
      color: #333;
      margin-bottom: 8px;
      font-weight: 500;
    }

    .book-tags {
      display: flex;
      gap: 6px;

      .tag {
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 12px;

        &.new-tag {
          background-color: #e6f7ff;
          color: #1890ff;
        }

        &.review-tag {
          background-color: #fff2e8;
          color: #fa8c16;
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;

  .empty-text {
    margin-top: 16px;
    font-size: 16px;
    color: #999;
  }
}

/* 新的任务卡片样式 */
.task-list {
  display: flex;
  flex-direction: column;
  gap: 12px;

  .task-card {
    display: flex;
    align-items: center;
    padding: 12px;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    position: relative;
    transition: all 0.3s;

    &:active {
      transform: scale(0.98);
    }

    &.completed {
      background-color: #f8f9fa;

      .task-title {
        color: #999;
        text-decoration: line-through;
      }
    }

    &.skipped {
      background-color: #f8f9fa;

      .task-title {
        color: #999;
      }
    }

    .task-status {
      margin-right: 12px;

      .status-icon {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;

        &.completed {
          background-color: #52c41a;
        }

        &.skipped {
          background-color: #ff4d4f;
        }

        &.pending {
          border: 2px solid #007aff;

          .pending-dot {
            width: 8px;
            height: 8px;
            background-color: #007aff;
            border-radius: 50%;
          }
        }
      }
    }

    .task-cover {
      width: 60px;
      height: 60px;
      border-radius: 8px;
      margin-right: 12px;
      background-color: #f5f5f5;
    }

    .task-info {
      flex: 1;

      .task-title {
        font-size: 16px;
        color: #333;
        margin-bottom: 6px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .task-meta {
        display: flex;
        align-items: center;
        gap: 8px;

        .task-type {
          font-size: 12px;
          padding: 2px 8px;
          border-radius: 4px;
          background-color: #e6f7ff;
          color: #1890ff;

          &.review {
            background-color: #f6ffed;
            color: #52c41a;
          }
        }

        .completed-time {
          font-size: 12px;
          color: #999;
        }
      }
    }

    .task-actions {
      padding: 8px;
      border-radius: 50%;

      &:active {
        background-color: #f5f5f5;
      }
    }
  }
}

/* 更新日期头部样式 */
.daily-task .day-header {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 12px;
  margin-bottom: 15px;

  .day-info {
    .day-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
      margin-bottom: 4px;
    }

    .day-subtitle {
      font-size: 14px;
      color: #666;
    }
  }

  .day-progress {
    display: flex;
    align-items: center;
    gap: 8px;

    .progress-text {
      font-size: 14px;
      color: #666;
      min-width: 40px;
      text-align: right;
    }

    .progress-bar {
      width: 60px;
      height: 6px;
      background-color: #e9ecef;
      border-radius: 3px;
      overflow: hidden;

      .progress-fill {
        height: 100%;
        background-color: #007aff;
        transition: width 0.3s;
      }
    }
  }
}
</style>
